package xyz.penghaonan.wificonnect.message;

import com.google.gson.Gson;
import com.penghaonan.appframework.utils.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class MsgFactory {
    private static final String TAG = "MsgFactory";
    public static final int TYPE_CMD_REQUEST = 1001;
    public static final int TYPE_CMD_RESPONSE = 1002;
    public static final int TYPE_LOCATION_INFO_REQUEST = 1003;
    public static final int TYPE_LOCATION_INFO_RESPONSE = 1004;
    public static final int TYPE_REQUEST_KEEP_ALIVE = 1005;
    public static final int TYPE_RESPONSE_KEEP_ALIVE = 1006;
    private static final Gson gson = new Gson();

    public static IMsg createMsg(String data) {
        try {
//            Logger.i(TAG, "received string : " + data);
            JSONObject jsonObject = new JSONObject(data);
            int type = jsonObject.optInt("type");
            IMsg msg = gson.fromJson(jsonObject.optString("msg"), getClass(type));
            if (msg != null) {
                return msg;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String createMsgText(IMsg msg) {
        if (msg == null) {
            return null;
        }
        int type = msg.getType();
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", type);
            jsonObject.put("msg", gson.toJson(msg));
            String dataStr = jsonObject.toString();
            return URLEncoder.encode(dataStr, "utf-8") + "\n";
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Class<? extends IMsg> getClass(int type) {
        switch (type) {
            case TYPE_CMD_REQUEST:
                return CmdRequestMsg.class;
            case TYPE_LOCATION_INFO_REQUEST:
                return LocationInfoRequestMsg.class;
            case TYPE_LOCATION_INFO_RESPONSE:
                return LocationInfoResponseMsg.class;
            case TYPE_REQUEST_KEEP_ALIVE:
                return KeepAliveRequestMsg.class;
            case TYPE_RESPONSE_KEEP_ALIVE:
                return KeepAliveResponseMsg.class;
        }
        return null;
    }
}
